<template>
  <div class="user-avatar-dropdown">
    <Dropdown @on-click="handleClick">
      <Badge :dot="msgData.length>0">
        <Avatar :src="userHeadImg" v-if="userHeadImg" />
        <Avatar v-else icon="ios-person"/>
      </Badge>
      <Icon :size="18" type="md-arrow-dropdown"></Icon>
      <DropdownMenu slot="list" class="content-center">
        <DropdownItem name="zone">个人中心</DropdownItem>
        <DropdownItem name="msg">
          <Badge :count="msgData.length" class="wd100" v-if="msgData.length>0">消 息</Badge>
          <div v-else>消 息</div>
        </DropdownItem>
        <DropdownItem name="logout">退出登录</DropdownItem>
      </DropdownMenu>
    </Dropdown>
    <Drawer :title="drawer.title" :closable="false" class="dropdown-dom" :width="drawer.width"
            v-model="drawer.showDrawer">
      <div v-if="drawer.type==='msg'">
        <div v-if="item.title" v-for="(item,index) in msgData" :key="index" class="mg5">
          <Card>
            <div class="card-close" @click="clearMsg(item)">
              <i class="ivu-icon ivu-icon-ios-close"></i>
            </div>
            <Tooltip slot="title" :content="item.title" :max-width="200" class="pdr15">
              {{ item.title }}
            </Tooltip>
            <div @click="cardClick(item)" class="show-hand">
              <p>{{ item.content || '无内容' }}</p>
            </div>
          </Card>
        </div>
      </div>
      <div v-else-if="drawer.type==='zone'" class="zone" v-clickoutside="handleClose">
        <div class="content-center">
          <Avatar icon="ios-person"  :src="userHeadImg" v-if="userHeadImg" size="large" class="show-hand" @click.native="chooseImg"/>
          <Avatar icon="ios-person"  v-else size="large" class="show-hand" @click.native="chooseImg"/>
          <span class="name-input" v-if="showInput&&currentEditType==='name'">
           <Input v-model="userInfo.name" ref="nameInput"></Input>
          </span>
          <H1 class="pd5 ls5" v-else @dblclick="modifyName">{{ userInfo.name || '未设置' }}</H1>

          <span class="name-motto" v-if="showInput&&currentEditType==='motto'">
           <Input v-model="userInfo.motto" ref="nameMotto" clearable></Input>
          </span>
          <p class="describe-text pdX20" v-else @dblclick="modifyMotto">{{ userInfo.motto || '没什么想表达的' }}</p>
        </div>
        <div class="business-card">
          <Card class="card-content">
            <H3 slot="title">
              <Icon type="ios-cafe-outline"/>
              名片信息
            </H3>
            <p>
              <Icon type="md-person" class="pdr15"/>
              lc
            </p>
            <p @mouseenter="showEdit('bornDate')" @mouseleave="hiddenEdit('bornDate')">
              <Icon type="ios-calendar" class="pdr15"/>
              <DatePicker v-if="showInput&&currentEditType==='bornDate'" type="date" placeholder="选择出生日期"
                          class="date-choose" @on-change="changeDate"></DatePicker>
              <span v-else>{{ userInfo.bornDate }}</span>
              <Icon class="show-hand" type="ios-create-outline"
                    v-if="showEditBtn&&currentEditType==='bornDate'&&!showInput" @click="showInput=true"/>
            </p>
            <p @mouseenter="showEdit('gender')" @mouseleave="hiddenEdit('gender')">
              <span v-if="userInfo.gender==='1'||userInfo.gender===1">
                <Icon type="md-male" class="pdr15"/>男
              </span>
              <span v-else>
                <Icon type="md-female" class="pdr15"/>女
              </span>

              <Icon class="show-hand" type="ios-swap" @click="userInfo.gender=userInfo.gender===1||userInfo.gender==='1'?0:1"
                    v-if="showEditBtn&&currentEditType==='gender'"/>
            </p>
            <p>
              <Icon type="md-nutrition" class="pdr15"/>Excse公司-部门A
            </p>
            <p @mouseenter="showEdit('address')" @mouseleave="hiddenEdit('address')">
              <Icon type="md-planet" class="pdr15"/>
              <al-cascader v-if="showInput&&currentEditType==='address'" class="address-choose"
                           @on-change="addressChange" v-model="addressArr"/>
              <span v-else>{{ userInfo.address }}</span>
              <Icon class="show-hand" type="ios-create-outline"
                    v-if="showEditBtn&&currentEditType==='address'&&!showInput" @click="showInput=true"/>
            </p>
            <p @mouseenter="showEdit('phoneNum')" @mouseleave="hiddenEdit('phoneNum')">
              <Icon type="md-phone-portrait" class="pdr15"/>{{ userInfo.phoneNum }}
              <poptip
                v-if="currentEditType==='phoneNum'"
              >
            <div slot="content" >
            <Form ref="phoneForm" class="phone-form" :model="phoneVerify" :rules="phoneVerifyRule">
              <FormItem>
                <Input v-model="phoneVerify.phoneNum" placeholder="新的手机号">
                  <a slot="append"  @click="sendReplacePhoneMsg">获取验证码</a>
                </Input>
              </FormItem>
              <FormItem>
                <Input v-model="phoneVerify.msgCode" placeholder="验证码"></Input>
              </FormItem>
              <div>
                <FormItem>
                  <Button @click="currentEditType=''">取消</Button>
                  <Button type="primary" @click="replacePhone">确定</Button>
                </FormItem>
              </div>
            </Form>
          </div>
            <Icon class="show-hand" type="ios-create-outline" v-if="currentEditType==='phoneNum'"/>
            </poptip>
            </p>
            <p @mouseenter="showEdit('email')" @mouseleave="hiddenEdit('email')">
              <Icon type="md-mail" class="pdr15"/>
              <AutoComplete
                v-model="userInfo.email"
                v-if="showInput&&currentEditType==='email'"
                @on-search="mailSearch"
                @on-select="sureMail"
                clearable
                placeholder="请输入电子邮箱地址"
                style="width:200px">
                <Option v-for="item in mails" :value="item" :key="item">{{ item }}</Option>
              </AutoComplete>
              <span v-else>{{userInfo.email}}</span>
              <Icon class="show-hand" type="ios-create-outline" v-if="showEditBtn&&currentEditType==='email'&&!showInput"  @click="showInput=true"/>
            </p>
          </Card>
        </div>

        <div>

        </div>
      </div>
    </Drawer>
    <img-upload
      field="img"
      url="/api/sysFile/uploadImg"
      v-if="uploadShow"
      noSquare
      :modelValue.sync="uploadShow"
      @crop-upload-success="successUpload"
      img-format="png"
    >
    </img-upload>
  </div>
</template>

<script>
import './user.less'
import {mapActions} from 'vuex'
import imgUpload from '@/components/v-avatar';
// import {replacePhoneNum, sendReplaceMsg} from "@/api/user";

const clickoutside = {
  // 初始化指令
  bind(el, binding, vnode) {
    function documentHandler(e) {
      if (e.path.length > 14) {
        return false
      } else {
        binding.value(e)
      }
    }

    // 给当前元素绑定个私有变量，方便在unbind中可以解除事件监听
    el.__vueClickOutside__ = documentHandler
    document.addEventListener('click', documentHandler)
  },
  update() {
  },
  unbind(el, binding) {
    // 解除事件监听
    document.removeEventListener('click', el.__vueClickOutside__)
    delete el.__vueClickOutside__
  }
}

export default {
  name: 'User',
  props: {
    userAvatar: {
      type: String,
      default: null
    }
  },
  directives: {clickoutside},
  components: {imgUpload},
  data() {
    return {
      mails: [],
      userHeadImg: "",
      uploadShow: false,
      showEditBtn: false,
      currentEditType: "",
      showInput: false,
      addressArr: [],
      userInfo: {},
      phoneVerifyRule:{},
      phoneVerify:{
        phoneNum:"",
        msgCode:""
      },
      modifyStatus:false,
      drawer: {
        showDrawer: false,
        type: "",
        title: "",
        width: "25%",
      }
    }
  },
  computed: {
    msgData() {
      return this.$store.state.user.msgData
    }
  },
  created() {
    this.getUserData()
    this.getMessageData()
  },
  watch: {
    userInfo: {
      handler: function (val) {
        this.modifyStatus = true
      },
      deep: true
    }
  },
  methods: {
    ...mapActions([
      'handleLogOut',
      'getMsgData',
      'seenMessage',
      'replacePhoneNum',
      'sendReplaceMsg',
      'saveUserInfo',
      'getUserInfo',
      'getImgUrl',
    ]),

    handleClose() { // 点击除了页面其他地方关闭车型选择
      this.showInput = false
      if (this.modifyStatus&&this.drawer.showDrawer&&this.drawer.type==='zone'){
        this.saveUser()
      }
    },

    //上传成功
    successUpload(data,field){
        this.userInfo.avatar  = ""
        this.userInfo.avatar  = data.id
        this.saveUser()
        this.uploadShow = false
        this.getImgData(data.id)
    },

    getUserData() {
      this.getUserInfo({id:this.$store.state.user.userId}).then(res=>{
        this.userInfo = Object.assign({},res)
        this.modifyStatus = false
        this.getImgData(this.userInfo.avatar)
      })
    },

    //改变出生日期
    changeDate(dateStr, type) {
      this.userInfo.bornDate = dateStr
    },

    //改变居住地
    addressChange(data) {
      this.userInfo.address = data.map(m => m.name).join("-")
    },

    showEdit(type) {
      if (!this.showInput) {
        this.currentEditType = type
        this.showEditBtn = true
      }
    },
    hiddenEdit(type) {
      if (!this.showInput) {
        this.currentEditType = type
        this.showEditBtn = false
      }
    },

    //保存用户信息
    saveUser(){
      this.saveUserInfo(this.userInfo).then(res=>{
        if (res.code==='0'){
          this.modifyStatus = false
        } else {
          this.$Message.error(res.msg)
        }
      })
    },


    //选择头像
    chooseImg() {
      this.uploadShow = true
      console.log("选择头像")
    },


    modifyName() {
      this.showInput = true
      this.currentEditType = 'name'
      setTimeout(() => {
        this.$refs.nameInput.focus()
      }, 200)

    },

    modifyMotto() {
      this.showInput = true
      this.currentEditType = 'motto'
      setTimeout(() => {
        this.$refs.nameMotto.focus()
      }, 200)

    },


    cardClick(row) {
      switch (row.msgType) {
        case 1:
        case "1":
          this.$router.push({
            name: 'activiti-tasks'
          })
          break;
        default:
          console.log(row)
          break
      }
      this.clearMsg(row)
      this.drawer.showDrawer = false
    },

    clearMsg(row) {
      this.seenMessage({id: row.id}).then(res => {
        this.getMessageData()
      })
    },

    handleClick(name) {
      this.drawer.type = name
      switch (name) {
        case 'logout':
          this.handleLogOut().then(() => {
            this.$router.push({
              name: 'login'
            })
          })
          break;
        case 'zone':
          this.viewZone()
          break;
        case 'msg':
          this.viewMsg()
          break;
      }
    },
    //个人中心
    viewZone() {
      this.drawer.title = "个人中心"
      this.drawer.width = "30%"
      this.drawer.showDrawer = true
    },

    //获取消息通知
    getMessageData() {
      this.$store.commit('setMsgData', [])
      this.getMsgData({}).then(res => {
        if (res.code === '0') {
          this.$store.commit('setMsgData', res.data)
        }
      })
    },

    //打开消息记录侧滑
    viewMsg() {
      this.drawer.title = "消息记录"
      this.drawer.width = "25%"
      this.drawer.showDrawer = true
    },

    //邮箱输入联想
    mailSearch (value) {
      this.mails = !value || value.indexOf('@') >= 0 ? [] : [
        value + '@qq.com',
        value + '@sina.com',
        value + '@163.com'
      ];
    },

    sureMail(value){

      console.log(value)
    },

    //发送手机换绑短信
    sendReplacePhoneMsg(){
      let params = Object.assign({},this.userInfo)
      params.phoneNum = this.phoneVerify.phoneNum
      this.sendReplaceMsg(params).then(res=>{
        if (res.code==='0'){
          this.$Message.success(res.data)
        }else {
          this.$Message.error(res.msg)
        }
      })
    },

    //换绑手机
    replacePhone(){
      let params = Object.assign({},this.userInfo)
      params.phoneNum = this.phoneVerify.phoneNum
      params.msgCode = this.phoneVerify.msgCode
      this.replacePhoneNum(params).then(res=>{
        if (res.code==='0'){
          this.$Message.success("更换手机绑定成功！")
          this.userInfo = Object.assign(this.userInfo,res.data)
          this.currentEditType=''
        }else{
          this.$Message.error(res.msg)
        }
      })
    },

    //获取头像图片
    getImgData(id){
        this.getImgUrl({id:id}).then(res=>{
          if (res.status===200){
            this.userHeadImg = res.data
          }
        })
    },
  }
}
</script>

<style lang="less" scoped>
.user-avatar-dropdown {
  /deep/ .ivu-badge-dot {
    top: 16px;
    right: -2px;
  }

  /deep/ .vicp-wrap {
    border-radius: 25px;
    cursor: auto;

    .vicp-crop .vicp-crop-right .vicp-preview .vicp-preview-item span {
      display: none !important;
    }

    .vicp-operate a {
      //color: #2D8cF0 !important;
    }
  }
}


/deep/ .ivu-drawer-header-inner{
  font-size: 17px;
}

/deep/ .ivu-poptip-inner{
  border-radius: 16px !important;
}

/deep/ .ivu-select-dropdown{
  border-radius: 16px !important;
}

.phone-form{
  padding: 20px 0 0 0;
  text-align: center;
  button{
    margin: 5px;
  }
}

.dropdown-dom {

  .zone {
    height: 100%;

    /deep/ .ivu-avatar-large {
      width: 80px;
      height: 80px;
      line-height: 80px;
      border-radius: 40px;
    }

    .name-input {
      /deep/ input {
        border: none;
        height: 46px;
        width: 200px !important;
        font-size: 24px;
        font-weight: 600;
        letter-spacing: 2px;
      }
    }

    .name-motto {
      /deep/ input {
        border: none;
        font-size: 16px;
        letter-spacing: 2px;
      }
    }

    .business-card {
      padding: 10px 25px;

      .card-content {
        p {
          display: -webkit-box;
          padding: 5px 30px;
          font-size: 18px;
          .show-hand{
            margin-left: 20px;
          }
        }

        .date-choose {
          width: 200px;
          font-size: 16px;
        }

        .address-choose {
          width: 300px;
          font-size: 14px;
        }
      }
    }
  }

}

</style>
